/*
 * 对密码字符串加密，可以用SHA-1、MD5等
 */
package anttesttools.tools;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *
 * @author anttesttools
 */
public class Encrypt
{

    /**
     * @param bts
     * @return
     */
    private static String bytes2Hex(byte[] bts)
    {
        StringBuffer des = new StringBuffer("");
        String tmp = null;
        for (int i = 0; i < bts.length; i++)
        {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1)
            {
                des.append("0");
            }
            des.append(tmp);
        }
        return des.toString();
    }

    /**
     * @param msg 要加密的文本
     * @param algorithm 运算法则，如MD5、SHA-1等
     * @return
     */
    public static String doEncrypt(String msg, String algorithm)
    {
        MessageDigest md = null;
        String strDes = null;

        byte[] bt = msg.getBytes();
        try
        {
            if (algorithm == null || algorithm.equals(""))
            {
                algorithm = "MD5";
            }
            md = MessageDigest.getInstance(algorithm);
            md.update(bt);
            strDes = bytes2Hex(md.digest()); // to HexString
        }
        catch (NoSuchAlgorithmException e)
        {
            return null;
        }
        return strDes;
    }

    /**
     * 用SHA-1加密
     * @param msg
     * @return
     */
    public static String SHA1(String msg)
    {
        return doEncrypt(msg, "SHA-1");
    }

    public static String MD5(String msg)
    {
        return doEncrypt(msg, "MD5");
    }

    public static void main(String args[])
    {
        String s = SHA1("wj");
        System.out.println(s);
        System.out.println(s.length());

        s = MD5("wj");
        System.out.println(s);
        System.out.println(s.length());
    }
}
